<!--
 描述: 酷屏首页模板
 作者: Jack Chen
 日期: 2020-04-29
-->

<template>
    <div class="home-container">

        <div class="wrap" ref="editor">


            <div class="top"></div>


            <sinan />
            <seamless />
            <pyramid />

            <scrollArc />
            <szBar />
            <div style="width: 100%;">
                <ringPin style="width: 100%;" />
            </div>

            <!-- <rotateColorful /> -->
            <!-- <circleRunway />  -->
            <!-- <scanRadius />  -->

            <cakeLinkage />
            <pyramidTrend />
            <dynamicLine />

            <staffMix />
            <flashCloud />
            <ringPie />
            <colorfulRadar />

            <dynamicList />
            <bar3d />
            <colorfulArea />

            <rainbow />
            <!-- <gauge /> -->
            <waterPolo />
            <circleNesting />

            <div class="divider"></div>

        </div>

    </div>
</template>

<script>
import { screenSize } from '@/assets/js/utils'
import * as echarts from 'echarts';
export default {
    name: 'Home',
    components: {},


    data() {
        return {
            testData: '',
            os: false,//控制摄像头开关
            thisVideo: null,
            thisContext: null,
            // thisCancas: null,
            imgSrc: '',
            videoWidth: 600,
            videoHeight: 400,
        };
    },

    watch: {
        testData: function () {
            this.$notify.info({
                title: '消息',
                message: this.testData
            });
        }
    },

    mounted() {

        var Color = 'green';
        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom, 'dark');
        var option;

        function randomData() {
            now = new Date(+now + oneDay);
            value = value + Math.random() * 21 - 10;
            return {
                name: now.toString(),
                value: [
                    [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
                    Math.round(value)
                ]
            };
        }
        let data = [];
        let now = new Date(1997, 9, 3);
        let oneDay = 24 * 3600 * 1000;
        let value = Math.random() * 1000;
        for (var i = 0; i < 1000; i++) {
            data.push(randomData());
        }
        option = {


            animation: false,
            // grid: {
            //   top: 0,
            //   bottom: '10%',
            //   left: '12%',
            //   right: '6%'
            // },

            xAxis: {
                type: "category",
                boundaryGap: false,
                axisTick: {
                    show: false,
                },
                axisLabel: {
                    show: false,
                    formatter(val) {
                        return val.substr(11, 5);
                    },
                },
                data: this.hrtime
            },
            yAxis: [{
                type: 'value',
                max: 140,
                axisLine: {
                    show: true,
                },
                splitNumber: 4,
                splitLine: {
                    show: false
                },
                axisLabel: {
                    show: false
                }
            },
            {
                type: 'value',
                max: 140,
                axisLine: {
                    show: true,
                },
                splitNumber: 4,
                splitLine: {
                    show: false
                },
                axisLabel: {
                    show: false
                }
            }
            ],
            visualMap: {
                show: false,
                dimension: 1,
                pieces: [{
                    gte: 5,
                    lte: 950,
                    color: "#0BD2C8",
                },
                {
                    gt: 95,
                    color: "#f97f7f",
                },
                    // {
                    //   lt: 50,
                    //   color: "#f97f7f",
                    // },
                ],
            },
            series: [{
                type: "line",
                symbol: "none",
                markLine: {
                    symbol: 'none',
                    emphasis: {
                        disabled: true
                    },
                    data: [{
                        silent: false,
                        lineStyle: {
                            type: 'dashed',
                            color: '#7d888b',
                            opacity: 0.5
                        },
                        label: {
                            show: false
                        },
                        yAxis: 140
                    },
                    {
                        silent: false,
                        lineStyle: {
                            type: 'dashed',
                            color: '#7d888b',
                            opacity: 0.5
                        },
                        label: {
                            show: false
                        },
                        yAxis: 95.1
                    },
                    {
                        silent: false,
                        lineStyle: {
                            type: 'dashed',
                            color: '#7d888b',
                            opacity: 0.5
                        },
                        label: {
                            show: false
                        },
                        yAxis: 50
                    }
                    ]
                },
                data: this.hrdata,
                markArea: {
                    itemStyle: {
                        color: "#003b41",
                    },
                    data: [
                        [{
                            yAxis: 50,
                        },
                        {
                            yAxis: 95,
                        },
                        ],
                    ],
                },
            },],


            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    params = params[0];
                    var date = new Date(params.name);
                    return (
                        date.getDate() +
                        '/' +
                        (date.getMonth() + 1) +
                        '/' +
                        date.getFullYear() +
                        ' : ' +
                        params.value[1]
                    );
                },
                axisPointer: {
                    animation: false
                }
            },
            xAxis: {
                type: 'time',
                splitLine: {
                    show: false
                }
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, '100%'],
                splitLine: {
                    show: true
                }
            },
            series: [
                {
                    name: 'Fake Data',
                    type: 'line',
                    showSymbol: false,
                    data: data,
                    color: Color
                }
            ]
        };
        setInterval(function () {

            for (var i = 0; i < 5; i++) {
                data.shift();
                data.push(randomData());
                // var tempData =lastData.value[1]
                // console.log(tempData)
                // console.log(Color)
                // if (tempData >1000)
                // {Color = 'red';}
                // else {Color = 'green';}



            }
            myChart.setOption({
                series: [
                    {
                        // color:Color,
                        data: data
                    }
                ]
            });
        }, 1000);

        option && myChart.setOption(option);


    },
    created() {
        this.openCamera();
    },
    mounted() {
        screenSize(this.$refs.editor);
    },
    methods: {
        submitBtn() {
            console.log(this.imgSrc);
        },
        // 调用摄像头权限
        openCamera() {
            //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
            this.$nextTick(() => {
                const _this = this;
                this.os = false;//切换成关闭摄像头
                // this.thisCancas = document.getElementById('canvasCamera');
                // this.thisContext = this.thisCancas.getContext('2d');
                this.thisVideo = document.getElementById('videoCamera');
                // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
                if (navigator.mediaDevices === undefined) {
                    navigator.mediaDevices = {}
                }
                // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
                // 使用getUserMedia，因为它会覆盖现有的属性。
                // 这里，如果缺少getUserMedia属性，就添加它。
                if (navigator.mediaDevices.getUserMedia === undefined) {
                    navigator.mediaDevices.getUserMedia = function (constraints) {
                        // 首先获取现存的getUserMedia(如果存在)
                        let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
                        // 有些浏览器不支持，会返回错误信息
                        // 保持接口一致
                        if (!getUserMedia) {
                            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
                        }
                        // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
                        return new Promise(function (resolve, reject) {
                            getUserMedia.call(navigator, constraints, resolve, reject)
                        })
                    }
                }
                const constraints = {
                    audio: false,
                    video: { width: _this.videoWidth, height: _this.videoHeight, transform: 'scaleX(-1)' }
                };
                navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                    // 旧的浏览器可能没有srcObject
                    if ('srcObject' in _this.thisVideo) {
                        _this.thisVideo.srcObject = stream
                    } else {
                        // 避免在新的浏览器中使用它，因为它正在被弃用。
                        _this.thisVideo.src = window.URL.createObjectURL(stream)
                    }
                    _this.thisVideo.onloadedmetadata = function (e) {
                        _this.thisVideo.play()
                    }
                }).catch(err => {
                    this.$message({
                        message: '没有开启摄像头权限或浏览器版本不兼容',
                        type: 'warning'
                    });
                });
            });
        },
        //拍照按钮
        photographBtn() {
            // 点击，canvas画图
            this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight);
            // 获取图片base64链接
            // this.imgSrc = this.thisCancas.toDataURL('image/png');
        },
        //清空画布
        clearCanvas(id) {
            let c = document.getElementById(id);
            let cxt = c.getContext("2d");
            cxt.clearRect(0, 0, c.width, c.height);
        },
        //重置画布
        resetBtn() {
            this.imgSrc = "";
            this.clearCanvas('canvasCamera');
        },
        //关闭摄像头
        stopCamera() {
            if (this.thisVideo && this.thisVideo !== null) {
                this.thisVideo.srcObject.getTracks()[0].stop();
                this.os = true;//切换成打开摄像头
            }
        },

        // 打开串口，并且传输数据
        async openSerial() {
            console.log("-----------------------------------------------------------------")



            const port = await navigator.serial.requestPort();
            await port.open({ baudRate: 115200 }); // set baud rate
            const keepReading = true;
            const reader = port.readable.getReader();
            // const writer = port.writable.getWriter();
            // set how to write to device internally
            // const writeInt = setInterval(async () => {
            //   const commandframe = new Uint8Array([
            //     0x00,
            //     0xff /*...some bytes to be sent*/,
            //   ]);
            //   await writer.write(commandframe);
            // }, 3000); // send a frame every 3000ms
            let receivedData = '';
            while (port.readable && keepReading) {
                try {
                    while (true) {
                        const { value, done } = await reader.read('\n');
                        if (done) {
                            // Allow the serial port to be closed later.
                            reader.releaseLock();
                            // Allow the serial port to be closed later.
                            // writer.releaseLock();
                            break;
                        }

                        if (value) {


                            const str = String.fromCharCode(...value);
                            receivedData += str;

                            let index = receivedData.indexOf('\n');
                            if (index !== -1) {
                                console.log(receivedData.substring(0, index)); // 最新获取的数据
                                this.testData = receivedData.substring(0, index)
                                receivedData = receivedData.substring(index + 1);
                                console.log("输入一条获取的数据")
                            }


                        }
                    }
                } catch (error) {
                    // Handle non-fatal read error.
                    console.error(error);
                } finally {
                    console.log(port.readable, keepReading);
                }
            }
            // clearInterval(writeInt);
            await port.close();
            console.log("port closed");

            console.log("-----------------------------------------------------------------")
        },
    }
}
</script>

<style lang="scss" scoped>
.home-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

    .wrap {
        transform-origin: 0px 0px 0px;
        background: url(../assets/img/bj.jpg) no-repeat;
        background-size: contain;
        background-position: 50% 0;
        background-color: rgb(0, 0, 0);
        min-width: auto;
        width: 1920px;
        min-height: auto;
        height: 1080px;
        overflow: auto;

        .top {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 80px;
            background-color: transparent;
            background: url(../assets/img/top_nav.png) no-repeat;
            background-position: 65% 0;
            border: none;
            overflow: hidden;
        }

        .divider {
            position: absolute;
            left: 50px;
            top: 3253px;
            width: 90%;
            height: 50px;
            width: 300px;
            border: none;
            background: transparent;
        }

    }
}
</style>
